package org.example.service;

import com.client.BidirectionalServiceGrpc;
import com.client.ClientDemoRequest;
import com.client.ServerDemoResponse;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

/**
 * @Author wangjun
 * @Date 2025/3/18 17:27
 */
@GrpcService
public class BidirectionalServiceImpl extends BidirectionalServiceGrpc.BidirectionalServiceImplBase {

    @Override
    public StreamObserver<ClientDemoRequest> chat(StreamObserver<ServerDemoResponse> responseObserver) {

        // 返回一个 StreamObserver 用于处理客户端请求流
        return new StreamObserver<ClientDemoRequest>() {
            @Override
            public void onNext(ClientDemoRequest request) {
                try {
                    int j = 10 / 0;
                    // 收到客户端消息，发送响应
                    String clientMessage = request.getMessage();
                    System.out.println("服务端 1 收到: " + clientMessage);

                    // 构造并发送回复
                    ServerDemoResponse response = ServerDemoResponse.newBuilder()
                            .setReply("服务端 1 回复: " + clientMessage.toUpperCase())
                            .build();
                    responseObserver.onNext(response);
                    responseObserver.onCompleted();
                } catch (Exception e) {
                    // 捕获未处理的异常并封装
                    responseObserver.onError(Status.UNKNOWN
                            .withDescription("服务端内部错误: " + e.getMessage())
                            .withCause(e)  // 传递原始异常
                            .asRuntimeException()
                    );
                }
            }

            @Override
            public void onError(Throwable t) {
                System.err.println("服务端 1 流错误: " + t.getMessage());
            }

            @Override
            public void onCompleted() {
                // 客户端结束流，服务端也结束
                System.out.println("服务端 1 流结束");
            }
        };
    }
}
